package cn.org.itool.ws.framework.netty.channel;

import cn.org.itool.ws.framework.event.CloseEvent;
import cn.org.itool.ws.framework.event.OpenEvent;
import cn.org.itool.ws.framework.listener.WsListener;
import cn.org.itool.ws.framework.thread.ServiceThreadPool;
import cn.org.itool.ws.framework.ws.WsServer;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.RejectedExecutionException;

@ChannelHandler.Sharable
public class WsEventHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(WsEventHandler.class);

    private final WsListener wsListener = WsServer.WS_LISTENER;

    private final ServiceThreadPool serviceThreadPool;

    public WsEventHandler() {
        this.serviceThreadPool = ServiceThreadPool.getInstance(WsServer.NETTY_PROPERTIES);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof OpenEvent){
            handlerOpenEvent((OpenEvent) evt);
        }else if (evt instanceof CloseEvent) {
            handlerCloseEvent((CloseEvent) evt);
        }else{
            super.userEventTriggered(ctx, evt);
        }
    }

    private void handlerCloseEvent(CloseEvent event){
        Runnable task = () -> {
            try {
                wsListener.onClose(event);
            } catch (Exception ex) {
                LOGGER.error(" Ws listener 处理 closeEvent 事件异常", ex);
            }
        };

        try {
            serviceThreadPool.getExecutor().submit(task);
        } catch (RejectedExecutionException ex) {
            LOGGER.error("业务线程池工作队列已经满", ex);
        }
    }

    private void handlerOpenEvent(OpenEvent evt) {

        Runnable task = () -> {
            try {
               wsListener.onOpen(evt);
            } catch (Exception ex) {
                LOGGER.error(" Ws listener 处理 openEvent 事件异常", ex);
            }
        };
        try {
            serviceThreadPool.getExecutor().submit(task);
        } catch (RejectedExecutionException ex) {
            LOGGER.error("业务线程池工作队列已经满", ex);
        }
    }
}
